/**
 * Copyright (c) 2024-2025 National Fundamental Software of China Co., Ltd.
 *
 * You should have find a copy of NFSChina License. If not, please contact us
 * by email <os_support@nfschina>
 *
**/

#include "timezone.h"

#include <KSystemTimeZone>
#include <KTreeWidgetSearchLine>
#include <QDebug>
#include <Plasma/Svg>
#include<QStackedWidget>
#include "timedated_interface.h"
Timezone::Timezone(QWidget *parent,bool haveTimedated)
    : QWidget(parent)
    , m_haveTimedated(haveTimedated)
{
    setupUi(this);
    searchicon->setIcon(QIcon::fromTheme(QStringLiteral("search")));
    connect(tzonelist, &K4TimeZoneWidget::itemSelectionChanged, this, &Timezone::configChanged);
    tzonesearch->setTreeWidget(tzonelist);
}

void Timezone::load()
{
    QString currentTimeZone;
    if (m_haveTimedated) {
        OrgFreedesktopTimedate1Interface timeDatedIface(QStringLiteral("org.freedesktop.timedate1"),
                                                        QStringLiteral("/org/freedesktop/timedate1"),
                                                        QDBusConnection::systemBus());
        currentTimeZone = timeDatedIface.timezone();
    } else {
        
        currentTimeZone = KSystemTimeZones::local().name();
    }
    
    currentZone();

    tzonelist->setSelected(currentTimeZone, true);
    Q_EMIT timeChanged(false);

    m_initialTimezone = selectedTimeZone();//changed by gy
}

bool Timezone::hasTimezoneChanges() const {//changed by gy
    return m_initialTimezone != selectedTimeZone();
}

void Timezone::currentZone()
{
    KTimeZone localZone = KSystemTimeZones::local();

    if (localZone.abbreviations().isEmpty()) {
        m_local->setText(i18nc("%1 is name of time zone", "Current local time zone: %1", K4TimeZoneWidget::displayName(localZone)));
    } else {
        m_local->setText(i18nc("%1 is name of time zone, %2 is its abbreviation",
                               "Current local time zone: %1 (%2)",
                               K4TimeZoneWidget::displayName(localZone),
                               QString::fromUtf8(localZone.abbreviations().constFirst())));
    }
}

void Timezone::configChanged()
{
    Q_EMIT timeChanged(true);
}

QString Timezone::selectedTimeZone() const
{
    QStringList selectedZones(tzonelist->selection());
    if (!selectedZones.isEmpty()) {
        return selectedZones.first();
    }

    return QString();
}
